﻿using System;
using System.Configuration;

namespace HY.Common
{
    /// <summary>
    /// 获取app.config设置值
    /// </summary>
    public class AppConfig
    {
        /// <summary>
        /// 获取指定Key的值
        /// </summary>
        /// <param name="key">Key</param>
        /// <returns></returns>
        public static string GetValue(string key)
        {
            try
            {
                return ConfigurationManager.AppSettings[key];
            }
            catch
            {
                return string.Empty;
            }
        }
        /// <summary>
        /// 获取指定Key的值
        /// </summary>
        /// <param name="key">Key</param>
        /// <returns></returns>
        public static string GetValue(string key, string defaultValue)
        {
            try
            {
                return ConfigurationManager.AppSettings[key];
            }
            catch
            {
                return defaultValue;
            }
        }

        /// <summary>
        /// 获取指定Key的值，不存在或类型转换错误会抛出异常
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">Key</param>
        /// <returns></returns>
        public static T GetValue<T>(string key) where T : struct
        {
            return (T)Convert.ChangeType(ConfigurationManager.AppSettings[key], typeof(T));
        }

        /// <summary>
        /// 获取指定Key的值，不存在或类型转换错误会返回默认值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">Key</param>
        /// <param name="objectValue"></param>
        /// <returns></returns>
        public static T GetValue<T>(string key, T objectValue) where T : struct
        {
            T result;
            try
            {
                result = (T)Convert.ChangeType(ConfigurationManager.AppSettings[key], typeof(T));
            }
            catch
            {
                result = objectValue;
            }
            return result;
        }
    }
}
